import { _decorator, Component, Node, Prefab, instantiate, Vec3, random } from 'cc';
import { GameConfig } from '../config/GameConfig';

const { ccclass, property } = _decorator;

@ccclass('FoodSpawnSystem')
export class FoodSpawnSystem extends Component {
    @property([Prefab])
    private foodPrefabs: Prefab[] = [];

    @property
    private spawnInterval: number = 2;

    @property
    private maxFoodCount: number = 50;

    private timer: number = 0;
    private currentFoodCount: number = 0;

    update(deltaTime: number) {
        this.timer += deltaTime;
        if (this.timer >= this.spawnInterval) {
            this.timer = 0;
            this.trySpawnFood();
        }
    }

    private trySpawnFood() {
        if (this.currentFoodCount >= this.maxFoodCount) return;

        // 随机选择一个食物预制体
        const randomIndex = Math.floor(Math.random() * this.foodPrefabs.length);
        const foodPrefab = this.foodPrefabs[randomIndex];

        // 随机生成位置
        const mapSize = GameConfig.GAME.MAP_SIZE;
        const x = (Math.random() - 0.5) * mapSize;
        const y = (Math.random() - 0.5) * mapSize;

        // 生成食物
        const food = instantiate(foodPrefab);
        food.setPosition(new Vec3(x, y, 0));
        this.node.addChild(food);
        this.currentFoodCount++;

        // 监听食物销毁
        food.once(Node.EventType.NODE_DESTROYED, () => {
            this.currentFoodCount--;
        });
    }
} 